<template>
  <view class="port-choose-container">
    <!-- 顶部导航 -->
    <ob-navbar title="选择目的港" :show-back="true" background-color="#FFFFFF" title-color="#333" :border="true" />

    <!-- 搜索框 -->
    <view class="search-section">
      <view class="search-box">
        <text class="search-icon">🔎</text>
        <input class="search-input" type="text" v-model="searchKeyword" placeholder="搜索港口名称或代码" @input="onSearchInput" />
        <text v-if="searchKeyword" class="clear-icon" @click="clearSearch">✕</text>
      </view>
    </view>

    <!-- 国家列表 -->
    <view class="card country-card" v-if="false">
      <view class="card-hd">
        <text class="title">选择国家</text>
        <text class="sub">点击国家查看对应港口</text>
      </view>
      <view class="country-list" v-if="countries.length">
        <view class="country-item" v-for="c in countries" :key="c.id">
          <view class="country-left">
            <view class="country-avatar">{{ (c.name||'').slice(0,1) }}</view>
            <view class="country-info">
              <text class="c-name">{{ c.name }}</text>
              <text class="c-en">{{ c.nameEn }}</text>
              <view class="count-chip">{{ c.portCount || 0 }} 个港口</view>
            </view>
          </view>
          <button class="btn btn-primary" @click="chooseCountry(c.id)">选择</button>
        </view>
      </view>
      <ob-empty v-else :image="'/static/images/empty-search.png'" title="暂无国家" description="请稍后再试" />
    </view>

    <!-- 统计卡片（当已选择国家） -->
    <view v-if="false" class="stats-row">
      <view class="stat">
        <text class="num">{{ portList.length }}</text>
        <text class="label">个港口</text>
      </view>
      <view class="stat">
        <text class="num">{{ selectedPort ? 1 : 0 }}</text>
        <text class="label">已选择</text>
      </view>
    </view>

    <!-- 港口列表 -->
    <view v-if="currentCountryId" class="card">
      <view class="card-hd">
        <text class="title">热门港口</text>
        <text class="sub">推荐港口，快速选择</text>
      </view>

      <!-- 加载中 -->
      <view v-if="isLoading" class="loading-state">
        <ob-loading :visible="true" text="加载中..." />
      </view>

      <!-- 空状态 -->
      <view v-else-if="filteredPorts.length === 0" class="empty-state">
        <ob-empty :image="'/static/images/empty-search.png'" title="未找到相关港口" description="请尝试其他关键词或切换国家" />
      </view>

      <!-- 列表 -->
      <view v-else class="port-list">
        <view v-for="p in filteredPorts" :key="p.id" class="port-item">
          <view class="left">
            <view class="port-avatar">{{ (p.name||'').slice(0,1) }}</view>
            <view class="info">
              <view class="row1">
                <text class="p-name">{{ p.name }}</text>
              </view>
              <view class="row2">
                <view class="chip"><text class="chip-icon">⚓</text>{{ p.code }}</view>
                <text class="country-text">{{ p.countryName }}</text>
              </view>
              <view class="desc">{{ p.description }}</view>
              <view class="meta">
                <view class="chip"><text class="chip-icon">🗺️</text>{{ p.region || '地区' }}</view>
                <view class="chip"><text class="chip-icon">⏱️</text>UTC{{ p.timezone ? ':' + p.timezone.replace('UTC','').replace('UTC+','+') : '+8' }}</view>
                <view v-if="p.services && p.services.length" class="chip"><text class="chip-icon">⚙️</text>{{ p.services.length }}项</view>
              </view>
              <view class="svc" v-if="p.hasWarehouse || p.hasCustoms || p.fastShipping">
                <view v-if="p.hasWarehouse" class="svc-chip">仓储服务</view>
                <view v-if="p.hasCustoms" class="svc-chip">港关服务</view>
                <view v-if="p.fastShipping" class="svc-chip">快捷物流</view>
              </view>
            </view>
          </view>
          <view class="right">
            <button class="btn btn-primary" @click="viewPortProducts(p)">选择港口</button>
          </view>
        </view>
      </view>
    </view>

    <!-- 热门港口 -->
    <view class="card" v-if="false">
      <view class="card-hd">
        <text class="title">热门港口</text>
        <text class="sub">推荐港口，快速选择</text>
      </view>
      <view class="port-list">
        <view v-for="hp in popularPorts" :key="hp.id" class="port-item">
          <view class="left">
            <view class="port-avatar hot">{{ (hp.name||'').slice(0,1) }}</view>
            <view class="info">
              <view class="row1">
                <text class="p-name">{{ hp.name }}</text>
                <view class="chip chip-hot">热</view>
              </view>
              <view class="row2">
                <view class="chip"><text class="chip-icon">⚓</text>{{ hp.code }}</view>
                <text class="country-text">{{ hp.countryName }}</text>
              </view>
              <view class="desc">{{ hp.description }}</view>
            </view>
          </view>
          <view class="right">
            <button class="btn btn-primary" @click="viewPortProducts(hp)">查看商品</button>
          </view>
        </view>
      </view>
    </view>

    <ob-loading :visible="isConfirming" text="设置中..." />
  </view>
</template>

<script setup>
import { ref, computed, inject, onMounted } from 'vue'
import { debounce } from '@/utils/common.js'
import portApi from '@/api/port.js'

const store = inject('$store')

const countries = ref([])
const currentCountryId = ref(null)
const searchKeyword = ref('')
const isLoading = ref(false)
const isConfirming = ref(false)
const portList = ref([])
const popularPorts = ref([])

const selectedPort = computed(() => store.state.selectedPort)

const filteredPorts = computed(() => {
  if (!searchKeyword.value) return portList.value
  const kw = searchKeyword.value.toLowerCase()
  return portList.value.filter(p =>
    (p.name||'').toLowerCase().includes(kw) ||
    (p.code||'').toLowerCase().includes(kw) ||
    (p.description||'').toLowerCase().includes(kw)
  )
})

onMounted(async () => {
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  const options = currentPage?.options || {}
  if (options.countryId) {
    currentCountryId.value = Number(options.countryId)
  }
  await loadCountries()
  await loadPopularPorts()
  if (currentCountryId.value) {
    await loadPorts()
    uni.pageScrollTo({ scrollTop: 0, duration: 0 })
  }
})

const onSearchInput = debounce(() => {}, 300)
const clearSearch = () => { searchKeyword.value = '' }

async function loadCountries() {
  try {
    const resp = await portApi.getCountriesWithPortCount()
    countries.value = Array.isArray(resp) ? resp : (resp?.records || [])
  } catch(e) { countries.value = [] }
}

async function chooseCountry(countryId) {
  currentCountryId.value = countryId
  await loadPorts()
  uni.pageScrollTo({ scrollTop: 0, duration: 200 })
}

async function loadPorts() {
  try {
    isLoading.value = true
    const resp = await portApi.getPortsByCountryId(currentCountryId.value)
    const ports = resp?.ports || resp?.data?.ports || []
    portList.value = ports.map(mapPort)
  } catch(e) {
    portList.value = []
  } finally { isLoading.value = false }
}

async function loadPopularPorts() {
  try {
    const list = await portApi.getPopularPorts()
    popularPorts.value = (Array.isArray(list) ? list : []).map(mapPort)
  } catch(e) { popularPorts.value = [] }
}

function mapPort(p) {
  return {
    id: p.id,
    name: p.name,
    code: p.portCode || p.code,
    description: p.description || '',
    region: p.region,
    timezone: p.timezone,
    isHot: p.isPopular === 1 || p.isPopular === true,
    services: p.services || [],
    hasWarehouse: Array.isArray(p.services) ? p.services.some(s => (s.name||'').includes('仓储')) : p.hasWarehouse,
    hasCustoms: Array.isArray(p.services) ? p.services.some(s => (s.name||'').includes('海关') || (s.name||'').includes('港关')) : p.hasCustoms,
    fastShipping: Array.isArray(p.services) ? p.services.some(s => (s.name||'').includes('快速') || (s.name||'').includes('快捷')) : p.fastShipping,
    countryName: p.countryName || p.country?.name
  }
}

function viewPortProducts(port) {
  // 设置选择的港口到全局状态
  store.actions.setSelectedPort(port)
  
  // 显示设置成功提示
  uni.showToast({
    title: `已切换到${port.name}`,
    icon: 'success',
    duration: 1000
  })
  
  // 直接跳转到首页，首页会自动加载该港口的推荐商品
  setTimeout(() => {
    uni.switchTab({
      url: '/pages/index/index'
    })
  }, 1000)
}

async function selectPort(port) {
  try {
    isConfirming.value = true
    store.actions.setSelectedPort(port)
    try { await portApi.setDefaultPort && portApi.setDefaultPort(port.id) } catch(e) {}
    uni.showToast({ title: '目的港设置成功', icon: 'success', duration: 1200 })
    setTimeout(() => { uni.navigateBack() }, 1200)
  } finally { isConfirming.value = false }
}
</script>

<style lang="scss" scoped>
.port-choose-container { min-height: 100vh; background:#F5F7FA; }
.search-section { background:#fff; padding: 12px 14px; border-bottom:1px solid #EEF2F7; }
.search-box { background:#FFFFFF; border:1px solid #E6ECF5; border-radius:14px; height:46px; display:flex; align-items:center; padding:0 12px; gap:10px; box-shadow: 0 1px 2px rgba(16,24,40,.04); }
.search-icon { color:#6B7280; font-size:16px; }
.search-input { flex:1; font-size:14px; color:#111827; }
.clear-icon { color:#9AA4B2; padding:4px; font-size:16px; }

.card { background:#fff; margin:12px; border-radius:14px; border:1px solid #EEF2F7; box-shadow: 0 6px 16px rgba(17,24,39,0.04); }
.card-hd { padding:16px 16px 0; }
.card-hd .title { font-weight:700; color:#0F172A; font-size:16px; display:block; }
.card-hd .sub { font-size:12px; color:#6B7280; display:block; margin-top:6px; }

.country-card .country-list { padding: 8px 14px 12px; }
.country-item { display:flex; align-items:center; justify-content:space-between; padding:16px 4px; border-bottom:1px solid #EEF2F7; }
.country-item:last-child { border-bottom: none; }
.country-left { display:flex; gap:14px; align-items:center; }
.country-avatar { width:56px; height:56px; border-radius:14px; background:#F4F7FF; color:#2F6BFF; display:flex; align-items:center; justify-content:center; font-weight:800; box-shadow: 0 6px 18px rgba(47,107,255,0.08); }
.country-info { display:flex; flex-direction:column; }
.c-name { font-size:15px; color:#0F172A; font-weight:700; }
.c-en { font-size:12px; color:#94A3B8; text-transform: uppercase; letter-spacing: .4px; }
.count-chip { margin-top:4px; display:inline-flex; padding:2px 8px; font-size:12px; background:#EEF4FF; color:#2F6BFF; border-radius:10px; }

.stats-row { display:flex; gap:12px; margin:12px; }
.stat { flex:1; background:#fff; border-radius:12px; padding:12px; box-shadow: 0 2px 8px rgba(31,45,61,0.06); display:flex; align-items:center; gap:10px; }
.stat .num { font-size:18px; font-weight:700; color:#111827; }
.stat .label { font-size:12px; color:#6B7280; }

.port-list { padding: 6px 14px 14px; display:flex; flex-direction:column; gap:12px; }
/* 预留右侧按钮空间，不影响正文布局 */
.port-item { position:relative; display:flex; gap:14px; padding:16px; background:#FFFFFF; border:1px solid #EEF2F7; border-radius:14px; box-shadow: 0 8px 24px rgba(17,24,39,0.06); }
.left { display:flex; gap:14px; flex:1; }
.port-avatar { width:56px; height:56px; border-radius:14px; background:#F4F7FF; display:flex; align-items:center; justify-content:center; color:#2F6BFF; font-weight:800; box-shadow: 0 6px 18px rgba(47,107,255,0.08); }
.port-avatar.hot { background:#FFF4E6; color:#FB923C; }
.info { flex:1; }
.row1 { display:flex; align-items:center; gap:8px; }
.p-name { font-size:16px; font-weight:800; color:#0F172A; }
.row2 { display:flex; align-items:center; gap:10px; margin:8px 0; }
.country-text { font-size:12px; color:#6B7280; }
.desc { background:#F7FAFF; color:#334155; padding:12px 14px; border-radius:10px; font-size:12px; border:1px solid #E6F0FF; box-shadow: 0 1px 2px rgba(17,24,39,0.04); line-height:1.6; }
.meta { display:flex; gap:12px; margin-top:10px; }
.chip { background:#EFF6FF; color:#2563EB; border-radius:12px; padding:2px 8px; font-size:12px; display:inline-flex; align-items:center; gap:6px; }
.chip-hot { position:absolute; top:12px; right:12px; background:#FFF7ED; color:#FB923C; border:1px solid #FED7AA; padding:2px 8px; border-radius:12px; font-weight:700; font-size:12px; }
.dot { width:6px; height:6px; background:#10B981; border-radius:50%; display:inline-block; }
.chip-icon { font-size:12px; margin-right:4px; }

/* 服务胶囊不压缩，自动换行排布 */
.svc { display:flex; flex-wrap:wrap; gap:12px; margin-top:12px; }
.svc-chip { background:#EAF4FF; color:#1D4ED8; border-radius:18px; padding:0 12px; font-size:12px; min-width:96px; height:36px; display:inline-flex; align-items:center; justify-content:center; white-space:nowrap; }

/* 按钮固定在右上方，避开“热”角标 */
.right { position:absolute; right:16px; top:44px; }
.btn { 
	border: none; 
	border-radius: 16px; 
	padding: 8px 18px; 
	height: auto;
	line-height: 1.2;
	font-size: 12px; 
	font-weight: 600; 
	cursor: pointer; 
	transition: all 0.2s ease;
	outline: none;
}
.btn-primary { 
	background: linear-gradient(135deg, #3B82F6 0%, #2563EB 100%); 
	color: #FFFFFF; 
	box-shadow: 0 2px 4px rgba(59,130,246,0.2);
}
.btn-primary:hover { 
	background: linear-gradient(135deg, #2563EB 0%, #1D4ED8 100%); 
	transform: translateY(-1px);
	box-shadow: 0 4px 8px rgba(59,130,246,0.3);
}
.btn-primary:active {
	transform: translateY(0px);
	box-shadow: 0 2px 4px rgba(59,130,246,0.2);
}


.loading-state, .empty-state { padding: 30px 0; }
</style>

